package com.zxbg.service.impl.systemtoolsServiceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxbg.dao.EmployeeDao;
import com.zxbg.dao.RoleDao;
import com.zxbg.domain.Employee;
import com.zxbg.domain.Role;
import com.zxbg.service.systemtoolsService.RoleManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;

@Service
public class RoleManagementServiceImpl implements RoleManagementService {
    @Autowired
    RoleDao roleDao;
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    OrganizationalStructureServiceImpl organizationalStructureService;

    @Override
    public List<Role> getAllRole(Map<String, Object> search_info, Integer tenant_id) {
        String KeyWord = "%" + ((String) search_info.get("keyWord")).replace("\"", "") + "%";
        List<Role> allRole = roleDao.getAllRole(KeyWord, tenant_id);
        List<Role> resList = new ArrayList<>();
        String jsonObject = JSON.toJSONString(search_info.get("creator"));
        Employee creator = JSONObject.parseObject(jsonObject, Employee.class);
        for (int i = 0; i < allRole.size(); i++) {
            Role role = allRole.get(i);
            if(creator != null && creator.getEmployee_id() != null && !role.getCreator_id().equals(creator.getEmployee_id())) {
                continue;
            }
            if(role != null && role.getPartner_id() != null && !role.getPartner_id().equals("")) {
                jsonObject = JSON.toJSONString(search_info.get("member"));
                Employee member = JSONObject.parseObject(jsonObject, Employee.class);
                String[] partnerIds = role.getPartner_id().split(",");
                if(member != null && member.getEmployee_id() != null && !Arrays.asList(partnerIds).contains(member.getEmployee_id())) {
                    continue;
                }
                List<Employee> employeeList = new ArrayList<>();
                for (int j = 0; j < partnerIds.length; j++) {
                    Employee temp = employeeDao.getEmployeeByEmployeeId(partnerIds[j], tenant_id);
                    if(temp != null) {
                        employeeList.add(temp);
                    }
                }
                role.setPartner(employeeList);
            }
            if(role.getAuthority_id() != null && !role.getAuthority_id().equals("")) {
                Map<String, List<String>> map = new HashMap<>();
                String[] allAuth = role.getAuthority_id().split(" & ");
                map.put("menu", Arrays.asList(allAuth[0].split(",")));
                map.put("authority", allAuth.length == 2 ? Arrays.asList(allAuth[1].split(",")) : new ArrayList<>());
                role.setAuthority(map);
            }
            role.setCreator(organizationalStructureService.getAllKindsDept(employeeDao.getEmployeeByEmployeeId(role.getCreator_id(), tenant_id)));
            resList.add(role);
        }
        return resList;
    }

    @Override
    public String addRole(Role role) {
        if(roleDao.getRoleByCode(role.getCode(), role.getTenant_id()) != null) {
            return "角色编码重复";
        }
        role.setCreator_id(role.getCreator().getEmployee_id());
        role.setPartner_id(getPartnerIds(role));
        return roleDao.addRole(role) > 0 ? "" : "添加失败";
    }

    @Override
    public boolean editRole(Role role) {
        List<String> oldPartner = new ArrayList<>();
        if(role.getCode().equals("sysadmin")) {
            String oldString = roleDao.getRoleByCode("sysadmin", role.getTenant_id()).getPartner_id();
            if(oldString != null && !oldString.equals("")) {
                oldPartner = Arrays.asList(oldString.split(","));
            }
        }
        String newString = getPartnerIds(role);
        List<String> newPartner = new ArrayList<>();
        if(newString != null && !newString.equals("")) {
            newPartner = Arrays.asList(newString.split(","));
        }
        if(oldPartner.size() > 0) {
            for (String oldP : oldPartner) {
                if(!newPartner.contains(oldP)) {
                    employeeDao.setIfSysadminByEmployeeId(oldP, 0, role.getTenant_id());
                }
            }
        }
        if(newPartner.size() > 0) {
            for (String newP : newPartner) {
                if(!oldPartner.contains(newP)) {
                    employeeDao.setIfSysadminByEmployeeId(newP, 1, role.getTenant_id());
                }
            }
        }
        role.setPartner_id(getPartnerIds(role));
        return roleDao.editRole(role) > 0;
    }

    public String getPartnerIds(Role role) {
        String partnerIds = "";
        if(role.getPartner() != null) {
            for (Employee employee : role.getPartner()) {
                partnerIds = partnerIds.equals("") ? employee.getEmployee_id() : partnerIds + "," + employee.getEmployee_id();
            }
        }
        if(partnerIds.equals("")) {
            return null;
        }
        return partnerIds;
    }

    @Override
    public boolean stopRole(String code, Integer tenant_id) {
        return roleDao.stopRole(code, tenant_id) > 0;
    }

    @Override
    public boolean runRole(String code, Integer tenant_id) {
        return roleDao.runRole(code, tenant_id) > 0;
    }

    @Override
    public boolean deleteRole(String code, Integer tenant_id) {
        return roleDao.deleteRole(code, tenant_id) > 0;
    }

    @Override
    public Map<String, Set> getAllAuth(String employee_id ,Integer tenant_id) {
        Map<String, Object> setMap = new HashMap<>();
        setMap.put("keyWord", "");
        setMap.put("creator", "");
        setMap.put("member", "");
        List<Role> roleList = getAllRole(setMap, tenant_id);
        List<Role> useList = new ArrayList<>();
        if(roleList.size() > 0) {
            for (Role role : roleList) {
                String authority_id = role.getAuthority_id();
                String partner_id = role.getPartner_id();
                if(authority_id != null && !authority_id.equals("") && partner_id != null && !partner_id.equals("") && role.getStatus() == 1) {
                    List<Employee> partners = role.getPartner();
                    for (Employee employee : partners) {
                        if(employee.getEmployee_id().equals(employee_id)) {
                            useList.add(role);
                            break;
                        }
                    }
                }
            }
        }
        Map<String, Set> res = new HashMap<>();
        res.put("menu", new HashSet());
        res.put("authority", new HashSet());
        if(useList.size() > 0) {
            for (Role role : useList) {
                res.get("menu").addAll(role.getAuthority().get("menu"));
                res.get("authority").addAll(role.getAuthority().get("authority"));
            }
        }
        return res;
    }

    @Override
    public boolean getIfSysadmin(String employee_id, Integer tenant_id) {
        if(employee_id.equals("sysadmin")) {
            return true;
        }
        Role sysadmin = roleDao.getRoleByCode("sysadmin", tenant_id);
        String partnerString = sysadmin.getPartner_id();
        if(partnerString != null && !partnerString.equals("")) {
            List<String> partner_ids = Arrays.asList(partnerString.split(","));
            if(partner_ids.contains(employee_id)) {
                return true;
            }
        }
        return false;
    }
}
